import styles from './sass/nav.scss'
import 'animate.css/animate.min.css'

import React, { Component } from 'react'

import axios from 'axios'
import Api from '../config/api'

import Button from 'antd/lib/button'
import Modal from 'antd/lib/modal'
import Icon from 'antd/lib/icon'
import message from 'antd/lib/message'
import Input from 'antd/lib/input'
import Form from 'antd/lib/form'
import List from 'antd/lib/list'

const confirm = Modal.confirm;
const FormItem = Form.Item;

//网页顶栏
class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sideCollapse: this.props.isCollapsed,
            userInfo: JSON.parse(localStorage.getItem('userInfo')),
            showModifyPModal: false,
            userInfoFlag: 'none',
            userInfoList: []
        }
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            sideCollapse: nextprops.isCollapsed
        })
    }
    componentDidMount() {
        let list = [{ title: 'id', data: this.state.userInfo.id, icon: 'key', color: '#9ACD32' }, { title: '真实姓名', data: this.state.userInfo.name, icon: 'user', color: '#36648B' }, { title: '手机号', data: this.state.userInfo.phone, icon: 'phone', color: '#CD950C' }, { title: '创建日期', data: this.state.userInfo.createTime.split(' ')[0], icon: 'calendar', color: '#8E388E' }];
        this.setState({
            userInfoList: list
        })
    }
    logout() {
        let that = this;
        confirm({
            title: '登出',
            content: '您确定要登出么？',
            okText: '登出',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                axios.post(Api['logout']).then((res) => {
                    if (res) {
                        sessionStorage.removeItem('isLogin')
                        message.success('登出成功，正在返回登陆页');
                        setTimeout(() => { that.props.history.replace('/login') }, 500);
                    }
                }).catch((error) => {
                    console.log(error)
                })
            },
            onCancel() { },
        });
    }
    toggleCollapsed() {
        this.props.toggleCollapsed();
    }
    handleShowModal() {
        this.props.form.resetFields()
        this.setState({
            showModifyPModal: true
        })
    }
    handleSure(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['modifyPassword'] + `?oldPwd=${data.oldPwd}&newPwd=${data.newPwd}`).then(response => {
                    if (response.data.code === '1') {
                        this.props.form.resetFields()
                        message.success('修改成功，请重新登陆');
                        setTimeout(() => { this.props.history.replace('/login') }, 500);
                    }
                    else {
                        message.error(response.data.desc)
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        });

    }
    handleCancel() {
        this.setState({
            showModifyPModal: false
        })
    }
    showUserInfo() {
        this.setState({
            userInfoFlag: 'block'
        })
    }
    hideUserInfo() {
        this.setState({
            userInfoFlag: 'none'
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <div className={styles.nav}>
                <div className={styles['nav-header-left'] + ' animated rubberBand'}>
                    <a style={{ color: '#fff' }} href="/main/home">
                        <img className={styles["youyu-logo"]} src={require('../assets/youyu-logo.png')} alt="youyu-logo" />
                        <span className={styles["nav-title"]}>展奎短信服务平台</span>
                    </a>
                </div>
                <div className={styles["nav-header-right"]}>
                    <span className={styles["user-name"]}>{'欢迎您，' + this.state.userInfo.account + '!'}</span>
                    <div style={{ position: 'relative' }}>
                        <img onMouseOver={this.showUserInfo.bind(this)} onMouseOut={this.hideUserInfo.bind(this)} className={styles["head-img"]} src={require('../assets/user-logo.png')} alt="head-img" />
                        <div className={styles['nav-user-info']} style={{ display: this.state.userInfoFlag }}>
                            <i className={styles["user-info-arrow"]}></i>
                            <div className={styles["user-info-head"]}>
                                <img className={styles["user-info-head-img"]} src={require('../assets/user-logo.png')} alt="head-img" />
                                <span className={styles["user-info-head-username"]}>{this.state.userInfo.account}</span>
                                {this.state.userInfo.roleId === 1 ? <Icon style={{ color: '#8B6914', marginLeft: '10px', fontSize: '26px' }} title="超级管理员" type="gitlab" /> : <Icon style={{ color: '#eee', marginLeft: '10px', fontSize: '26px' }} title="普通用户" type="gitlab" />}
                            </div>
                            <List
                                bordered
                                className={styles["user-info-list"]}
                                itemLayout="horizontal"
                                dataSource={this.state.userInfoList}
                                renderItem={item => (
                                    <List.Item>
                                        <List.Item.Meta
                                            avatar={<Icon type={item.icon} style={{ fontSize: '30px', color: item.color }} />}
                                            title={item.title}
                                            description={item.data}
                                        />
                                    </List.Item>
                                )}
                            />
                        </div>
                    </div>
                    <Icon type="safety" title="修改密码" className={styles["modify-password"]} onClick={this.handleShowModal.bind(this)} />
                    <div className={styles["nav-verticle-line"]}></div>
                    <Icon type="logout" title="登出" className={styles["logout"]} onClick={this.logout.bind(this)} />
                </div>
                <Modal visible={this.state.showModifyPModal} onCancel={this.handleCancel.bind(this)} wrapClassName="vertical-center-modal" title="修改密码" footer={[
                    <Button key="sure" type="primary" onClick={this.handleSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleCancel.bind(this)}>取消</Button>
                ]} >
                    <Form className="add-account-form">
                        <FormItem label="旧密码" {...formItemLayout}>
                            {getFieldDecorator('oldPwd', { rules: [{ required: true, message: '必填' }] })(<Input type="password" />
                            )}
                        </FormItem>
                        <FormItem label="新密码" {...formItemLayout}>
                            {getFieldDecorator('newPwd', { validateFirst: true, rules: [{ required: true, message: '必填' }, { max: 10, message: '10位以内' }, { pattern: /^([a-zA-z]|\d|_)+$/, message: '密码只能是字母、数字或下划线' }] })(<Input type="password" />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const ValidateBox = Form.create()(Box);

export default ValidateBox